package com.bobi.tfca.ui.mainnavigation.home.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.lifecycle.ViewModel
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentOrgActConditionBinding
import com.bobi.tfca.databinding.FragmentOrgActDetailsBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.ActivityAPI
import com.bobi.tfca.network.response.ActivityResponse
import com.bobi.tfca.network.response.ArticleResponse
import com.bobi.tfca.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class OrgActDetailsFragment : BaseFragment<FragmentOrgActDetailsBinding, ViewModel>(
    FragmentOrgActDetailsBinding::inflate,
    null,
    true
) {


    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentOrgActDetailsBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置顶部样式
        setTopPanelStyle(binding)

        binding.activityDetails.setText(publicViewModel!!.organizeActivity.activityDetails)

        // 在返回上一个页面的时候，将文字保存起来，最好是根据事件来算，而不是简单的上一步按钮，因为用户可能按系统功能键
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
            publicViewModel!!.organizeActivity.activityDetails = binding.activityDetails.text.toString()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }

        binding.previousStep.setOnClickListener {
            publicViewModel!!.organizeActivity.activityDetails = binding.activityDetails.text.toString()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }

        // 设置完成按钮
        binding.nextStep.setOnClickListener {
            // 创建确认框
            val builder = AlertDialog.Builder(requireContext())
            builder.setTitle("发布")
            builder.setMessage("你确认发布活动吗")

            // 设置确认按钮和点击事件
            builder.setPositiveButton("确认") { dialog, which ->
                publicViewModel!!.organizeActivity.activityDetails = binding.activityDetails.text.toString()
                organizeActivity(this, binding)
            }

            // 设置取消按钮和点击事件
            builder.setNegativeButton("取消") { dialog, which ->
            }

            // 创建并显示确认框
            val dialog: AlertDialog = builder.create()
            dialog.show()
        }
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentOrgActDetailsBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            publicViewModel!!.organizeActivity.activityDetails = binding.activityDetails.text.toString()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.text = "活动内容"
    }

    /**
     * 发送组织活动请求
     */
    private fun organizeActivity(
        fragment: OrgActDetailsFragment,
        binding: FragmentOrgActDetailsBinding
    ) {
        val activity = publicViewModel!!.organizeActivity
        publicViewModel!!.apply {
            request(ActivityAPI::class.java).organizeActivity(activity).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val code = it.data?.code
                                if (code == 200) {
                                    LogUtil.i("发布成功")
                                    val activityId = it.data?.data
                                    if (activityId != null) {
                                        Toast.makeText(requireActivity(), "活动创建成功", Toast.LENGTH_SHORT).show()
                                        publicViewModel!!.activity.value!!.activityId = activityId
                                        // 完后直接前往活动详情的fragment，参照之前的写法
                                        fragment.requireActivity().findNavController(R.id.app_nav).navigate(R.id.activityDetailsFragment, null,
                                            NavOptions.Builder().setPopUpTo(R.id.organizeActivityFragment, true)
                                                .build())
                                    }
                                } else {
                                    Toast.makeText(requireActivity(), "活动创建失败", Toast.LENGTH_SHORT).show()
                                }
                            }

                        }
                    }
                }
            }
        }

    }
}